package com.rongcheng.frc.newstyledemo.ui.player.audio;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;


import com.rongcheng.frc.newstyledemo.ui.player.constants.MediaPlayerStatus;

import java.io.IOException;


/**
 * 作用于YanxiuMp3PlayerActivity
 */
public class YanXiuMediaPlayer{
    private String TAG = "YanXiuMediaPlayer";
    private Uri mUri;
    private int mDuration;

    private int mCurrentState = MediaPlayerStatus.STATE_IDLE;
    private int mTargetState = MediaPlayerStatus.STATE_IDLE;

    private final int FORWARD_TIME = 5000;
    private final int REWIND_TIME = 5000;

    private MediaPlayer mMediaPlayer = null;
    private Context mContext;

    private boolean mCanPause;
    private boolean mCanSeekBack;
    private boolean mCanSeekForward;

    private MediaPlayer.OnCompletionListener mOnCompletionListener;
    private MediaPlayer.OnPreparedListener mOnPreparedListener;
    private VideoViewStateChangeListener mStateChangeListener;
    private int mCurrentBufferPercentage;
    private MediaPlayer.OnErrorListener mOnErrorListener;



    public void setVideoURI(Uri uri) {
        mUri = uri;
        openVideo();
        // setVisibility(View.VISIBLE);
    }

    public YanXiuMediaPlayer(Context context) {
        this.mContext = context;
        initVideoView();
    }

    private void initVideoView() {
        mCurrentState = MediaPlayerStatus.STATE_IDLE;
        StateChange(mCurrentState);
        mTargetState = MediaPlayerStatus.STATE_IDLE;
    }
    private void StateChange(int mCurrentState) {
        if (mStateChangeListener != null) {
            mStateChangeListener.onChange(mCurrentState);
        }
    }

    private void openVideo() {
        if (mUri == null) {
            // not ready for playback just yet, will try again later
            return;
        }
        // Tell the music playback service to pause
        // TODO: these constants need to be published somewhere in the
        // framework.
        Intent i = new Intent("com.android.music.musicservicecommand");
        i.putExtra("command", "pause");
        mContext.sendBroadcast(i);

        release(false);
        try {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setOnPreparedListener(mPreparedListener);
            mDuration = -1;
            mMediaPlayer.setOnCompletionListener(mCompletionListener);
            mMediaPlayer.setOnErrorListener(mErrorListener);
            mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
            mCurrentBufferPercentage = 0;
            mMediaPlayer.setDataSource(mContext, mUri);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setScreenOnWhilePlaying(true);
            mMediaPlayer.prepareAsync();
            // we don't set the target state here either, but preserve the
            // target state that was there before.
            mCurrentState = MediaPlayerStatus.STATE_PREPARING;
            StateChange(mCurrentState);
        } catch (IOException ex) {
            Log.w(TAG, "Unable to open content: " + mUri, ex);
            mCurrentState = MediaPlayerStatus.STATE_ERROR;
            StateChange(mCurrentState);
            mTargetState = MediaPlayerStatus.STATE_ERROR;
            mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
            return;
        } catch (IllegalArgumentException ex) {
            Log.w(TAG, "Unable to open content: " + mUri, ex);
            mCurrentState = MediaPlayerStatus.STATE_ERROR;
            StateChange(mCurrentState);
            mTargetState = MediaPlayerStatus.STATE_ERROR;
            mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
            return;
        }
    }

    /*
     * release the media player in any state
     */
    private void release(boolean cleartargetstate) {
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer.release();
            mMediaPlayer = null;
            mCurrentState = MediaPlayerStatus.STATE_IDLE;
            StateChange(mCurrentState);
            if (cleartargetstate) {
                mTargetState = MediaPlayerStatus.STATE_IDLE;
            }
        }
    }


    MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
        public void onPrepared(MediaPlayer mp) {
            start();
            mCurrentState = MediaPlayerStatus.STATE_PREPARED;
            StateChange(mCurrentState);
            mCanPause = mCanSeekBack = mCanSeekForward = true;

            if (mOnPreparedListener != null) {
                mOnPreparedListener.onPrepared(mMediaPlayer);
            }

        }
    };
    public void start() {
        if(mMediaPlayer != null){
            mMediaPlayer.start();
            mCurrentState = MediaPlayerStatus.STATE_PLAYING;
            StateChange(mCurrentState);
            mTargetState = MediaPlayerStatus.STATE_PLAYING;
            StateChange(MediaPlayerStatus.STATE_ENFORCEMENT);
        }
    }

    public void pause() {
        if (isInPlaybackState()) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();
                mCurrentState = MediaPlayerStatus.STATE_PAUSED;
                StateChange(mCurrentState);
            }
        }
        mTargetState = MediaPlayerStatus.STATE_PAUSED;
    }
    public void stopPlayback() {
        StateChange(MediaPlayerStatus.STATE_STOPBACK);// 涓虹粺璁″姞鍏�
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
            mCurrentState = MediaPlayerStatus.STATE_IDLE;
            StateChange(mCurrentState);
            mTargetState = MediaPlayerStatus.STATE_IDLE;
        }
    }

    // cache duration as mDuration for faster access
    public int getDuration() {
        if (isInPlaybackState()) {
            if (mDuration > 0) {
                return mDuration;
            }
            mDuration = mMediaPlayer.getDuration();
            return mDuration;
        }
        mDuration = -1;
        return mDuration;
    }

    public boolean isPlaying(){
        if(mMediaPlayer != null)
            return mMediaPlayer.isPlaying();
        else
            return false;
    }



    public void seekTo(int msec) {
        if(mMediaPlayer!=null){
            if (msec < 1000) {
                msec = 1000;
            }
            if (isInPlaybackState()) {
                mMediaPlayer.seekTo(msec);
            }
        }
    }

    public void forward() {
        if(mMediaPlayer != null){
            int last = mMediaPlayer.getCurrentPosition() + REWIND_TIME;
            if (last > mMediaPlayer.getDuration() - FORWARD_TIME){
                last = mMediaPlayer.getDuration() - FORWARD_TIME;
            }
            seekTo(last);
        }
    }
    public void rewind() {
        if(mMediaPlayer != null){
            int last = mMediaPlayer.getCurrentPosition() - REWIND_TIME;
            if (last < 0){
                last = 0;
            }
            seekTo(last);
        }
    }

    public int getCurrentPosition() {
        if (mMediaPlayer!=null && isInPlaybackState()) {
            return mMediaPlayer.getCurrentPosition();
        }
        return 0;
    }

    public boolean isInPlaybackState() {
        return (mMediaPlayer != null && mCurrentState != MediaPlayerStatus.STATE_ERROR && mCurrentState != MediaPlayerStatus.STATE_IDLE && mCurrentState != MediaPlayerStatus.STATE_PREPARING);
    }




    private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
            mCurrentState = MediaPlayerStatus.STATE_PLAYBACK_COMPLETED;
            StateChange(mCurrentState);
            mTargetState = MediaPlayerStatus.STATE_PLAYBACK_COMPLETED;
            mCurrentState = MediaPlayerStatus.STATE_STOPBACK;
            StateChange(mCurrentState);// 鏈粺璁″姞鍏�
            if (mOnCompletionListener != null) {
                mOnCompletionListener.onCompletion(mMediaPlayer);
            }
        }
    };

    private MediaPlayer.OnErrorListener mErrorListener = new MediaPlayer.OnErrorListener() {
        public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
            Log.d(TAG, "Error: " + framework_err + "," + impl_err);
            mCurrentState = MediaPlayerStatus.STATE_ERROR;
            StateChange(mCurrentState);
            mTargetState = MediaPlayerStatus.STATE_ERROR;

			/* If an error handler has been supplied, use it and finish. */
            if (mOnErrorListener != null) {
                if (mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err)) {
                    return true;
                }
            }

			/*
			 * Otherwise, pop up an error dialog so the user knows that
			 * something bad has happened. Only try and pop up the dialog if
			 * we're attached to a window. When we're going away and no longer
			 * have a window, don't bother showing the user an error.
			 */
            // if (getWindowToken() != null) {
            //
            // // Resources r = mContext.getResources();
            // // int messageId;
            // //
            // // if (framework_err ==
            // // MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
            // // messageId =
            // //
            // com.android.internal.R.string.VideoView_error_text_invalid_progressive_playback;
            // // } else {
            // // messageId =
            // // com.android.internal.R.string.VideoView_error_text_unknown;
            // // }
            // //
            // // new AlertDialog.Builder(mContext)
            // // .setTitle(com.android.internal.R.string.VideoView_error_title)
            // // .setMessage(messageId)
            // //
            // .setPositiveButton(com.android.internal.R.string.VideoView_error_button,
            // // new DialogInterface.OnClickListener() {
            // // public void onClick(DialogInterface dialog, int whichButton)
            // // {
            // // /* If we get here, there is no onError listener, so
            // // * at least inform them that the video is over.
            // // */
            // // if (mOnCompletionListener != null) {
            // // mOnCompletionListener.onCompletion(mMediaPlayer);
            // // }
            // // }
            // // })
            // // .setCancelable(false)
            // // .show();
            // }
            return true;
        }
    };

    private MediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() {
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            mCurrentBufferPercentage = percent;
        }
    };


    public interface VideoViewStateChangeListener {
        public void onChange(int mCurrentState);
    }


    public void setStateChangeListener(VideoViewStateChangeListener mStateChangeListener) {
        this.mStateChangeListener = mStateChangeListener;
    }







}
